package main

//简单演示go操作mongo的，find &delete
import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

const (
	mongoUri = "mongodb://10.70.30.73:27018"
)

//任务时间节点：注意别名需要用""引号括起来
type timePoint struct {
	StartTime int64 `bson:"start_time"`
	EndTime   int64 `bson:"end_time"`
}

type DocJobLog struct {
	//如果不指定后面的``标签内容，将会把字段名称变为小写，此处写json无效，
	Name         string    `bson:"name"`
	Command      string    `bson:"command"`
	RelationTime timePoint `bson:"relation_time"`
	Err          string    `bson:"error"`
	ExecResult   string    `bson:"exec_result"`
}

//定义一个结构体来序列化查询条件，自动转bson
type FindByJobName struct {
	JobName string `bson:"name"`
}

//k:v={"$lt",time.now().unix},注意是通过tag标签来定义key，而value 为前面的字段值
type TimeBeforeCondition struct {
	Before int64 `bson "$lt"`
}

//k:v=({timePoint.startTime:{"$lt",time.now().unix}})
type DeleteCondition struct {
	timeBeforeCondition TimeBeforeCondition `bson "timePoint.startTime"`
}

func main() {
	var (
		err           error
		findCursor    *mongo.Cursor
		findCondition *FindByJobName
		limitNum      int64
		skipNum       int64

		deleCon      *DeleteCondition
		deleteResult *mongo.DeleteResult
	)

	client, err := mongo.NewClient(options.Client().ApplyURI(mongoUri))
	err = client.Connect(context.TODO())
	if err != nil {
		fmt.Println(err)
	}
	database := client.Database("my_db")
	collection := database.Collection("my_collection")

	findCondition = &FindByJobName{JobName: "hi"}
	//// 将 int64 转化为 *int64
	//int64Num := int64(2)
	//limitNum := (*int64)(unsafe.Pointer(&int64Num))
	//findCursor, err = collection.Find(context.TODO(), findCondition,
	//	&findOptions.FindOptions{
	//		AllowPartialResults: nil,
	//		BatchSize:           nil,
	//		Collation:           nil,
	//		Comment:             nil,
	//		CursorType:          nil,
	//		Hint:                nil,
	//		Limit:               limitNum,
	//		Max:                 nil,
	//		MaxAwaitTime:        nil,
	//		MaxTime:             nil,
	//		Min:                 nil,
	//		NoCursorTimeout:     nil,
	//		OplogReplay:         nil,
	//		Projection:          nil,
	//		ReturnKey:           nil,
	//		ShowRecordID:        nil,
	//		Skip:                nil,
	//		Snapshot:            nil,
	//		Sort:                nil,
	//	})

	limitNum = 3
	skipNum = 2
	findOptions := &options.FindOptions{Skip: &skipNum, Limit: &limitNum}
	findCursor, err = collection.Find(context.TODO(), findCondition, findOptions)
	//延迟关闭游标
	findCursor.Close(context.TODO())
	//处理游标
	for findCursor.Next(context.TODO()) {
		record := &DocJobLog{}
		if err = findCursor.Decode(record); err != nil {
			fmt.Println(err)
		}
		fmt.Println(*record)
	}

	//删除操作，删除当天时间之前，返回
	deleCon = &DeleteCondition{timeBeforeCondition: TimeBeforeCondition{Before: time.Now().Unix()}}

	if deleteResult, err = collection.DeleteMany(context.TODO(), deleCon); err != nil {
		fmt.Println(err)
	}
	fmt.Println("删除行数", deleteResult.DeletedCount)
}
